package com.sml.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sml.mapper.ArticleMapper;
import com.sml.pojo.Article;
import com.sml.pojo.PageBean;
import com.sml.service.ArticleService;
import com.sml.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Service
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    private ArticleMapper articleMapper;

    /**
     * 新增文章
     *
     * @param article 文章对象
     */
    @Override
    public void add(Article article) {
        // 补充属性-创建时间和更新时间
        article.setCreateTime(LocalDateTime.now());
        article.setUpdateTime(LocalDateTime.now());
        // 补充属性-创建人id
        Map<String, Object> c = ThreadLocalUtil.get();
        Integer userId = (Integer) c.get("id");
        article.setCreateUser(userId);
        articleMapper.add(article);
    }

    @Override
    public PageBean<Article> list(Integer pageNum, Integer pageSize, Integer categoryId, String state) {
        //创建PageBean对象
        PageBean<Article> pb = new PageBean<>();
        //开启分页查询--PageHelper插件
        PageHelper.startPage(pageNum, pageSize);
        //查询当前登录用户的文章列表
        Map<String, Object> objectMap = ThreadLocalUtil.get();
        //获取当前登录用户id
        Integer userId = (Integer) objectMap.get("id");
        //调用mapper
        List<Article> as = articleMapper.list(userId, categoryId, state);
        //Page中提供了方法，可以获取PageHelper分页查询的结果，得到总记录数和分页数据
        Page<Article> p = (Page<Article>) as;
        //设置PageBean属性值
        pb.setTotal(p.getTotal());
        pb.setItems(p.getResult());
        return pb;
    }
}
